package org.tinygame.herostory.cmdHandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinygame.herostory.async.AsyncOperationProcessor;
import org.tinygame.herostory.login.LoginService;
import org.tinygame.herostory.login.db.UserEntity;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

/**
 * 用户登录指定处理器
 *
 * @author shkstart
 * @create 2022-05-07 15:11
 */
public class UserLoginCmdHandler implements ICmdHandler<GameMsgProtocol.UserLoginCmd> {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserLoginCmdHandler.class);

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserLoginCmd cmd) {
        if (null == ctx || null == cmd) {
            return;
        }
        LOGGER.info("用户登录，userName={},password={}", cmd.getUserName(), cmd.getPassword());

        LoginService.getInstance().userLogin(cmd.getUserName(), cmd.getPassword(), (userEntity) -> {
            if (null == userEntity) {
                LOGGER.error("用户登陆失败，userName={}", cmd.getUserName());
                return null;
            }
            //userLogin中与数据库iO的部分是在异步线程中完成，之后回到主线程
            LOGGER.info("当前线程= {}",Thread.currentThread().getName());

            LOGGER.info(
                    "用户登陆成功，userId= {}, userName= {}", userEntity.userId, userEntity.userName
            );

            //登陆时，构建新用户
            User newUser = new User();
            newUser.userId = userEntity.userId;
            newUser.userName = userEntity.userName;
            newUser.heroAvatar = userEntity.heroAvatar;
            newUser.currHp = 100;
            //将新用户加入用户管理器
            UserManager.addUser(newUser);

            //将用户id附着到channel,用于人物移动
            ctx.channel().attr(AttributeKey.valueOf("userId")).set(newUser.userId);

            GameMsgProtocol.UserLoginResult.Builder resultBuilder = GameMsgProtocol.UserLoginResult.newBuilder();
            resultBuilder.setUserId(newUser.userId);
            resultBuilder.setUserName(newUser.userName);
            resultBuilder.setHeroAvatar(newUser.heroAvatar);

            //构建结果并发送
            GameMsgProtocol.UserLoginResult newResult = resultBuilder.build();
            ctx.writeAndFlush(newResult);
            return null;
        });


    }
}
